<?php
/**
 * XuYuan Project
 *
 * @package	XueYuan 
 * @author	Jiuchi Team
 * @since	Version 1.0.0
 * @filesource
 */
defined('BASEPATH') OR exit('No direct script access allowed');
/**
 * User controller class
 * @author Wayne Yu
 */
class Circle extends CI_Controller {
	public function __construct(){
		parent::__construct();
		$this->load->library('session');
		$this->load->library('apioutput');
		$this->load->library('msgblock');
		$this->load->helper('url');
		$uid = $this->session->userdata('uid');
		if(empty($uid)){
			redirect(site_url('login'));
		}
		$this->load->model('user_model');
		$this->load->model('circle_model');
		$this->load->model('circle_category_model');
		$this->load->model('circle_user_model');
		$this->load->model('circle_admin_model');
		$this->load->model('circle_applicant_model');
		$this->load->model('topic_model');
		$this->load->model('user_dynamic_model');
	}
	
	/**
	 * Personal center dashboard
	 */
	public function index(){
		$data = array();
		$this->load->view('circle/index', $data);
	}
	
	public function all($cateId = ''){
		$circleCategory = $this->circle_category_model->retrieve();

		$cateId = $this->input->get('categoryId');
		$keyword = $this->input->get('keyword');
		$data = array(
				'cirCate'	=>	$circleCategory,
				'cateId'	=>	$cateId,
				'keyword'	=>	$keyword
		);
		$this->load->view('circle/all', $data);
	}	
	
	/**
	 * Create page
	 */
	public function create(){
		$circleCategory = $this->circle_category_model->retrieve();
		$data = array(
				'cirCate'	=>	$circleCategory
		);
		$this->load->view('circle/createCircle', $data);
	}
	
	/**
	 * create circle post
	 */
	public function createPost(){
		$input = $this->input->post();
		if(empty($input['name'])|| empty($input['category']) || empty($input['description'])){
			die("<script>alert('该圈名已被创建！');window.location.href='".site_url('circle/create')."';</script>");
		}
		$data = array(
				'circle_category_id'	=>	$input['category'],
				'name'					=>	$input['name'],
				'description'			=>	$input['description'],
				'user_number'			=>	1,
				'creator'				=>	$this->session->userdata('uid')
		);

		if($this->circle_model->checkCircleName($data['name']) == FALSE){
			die("<script>alert('该圈名已被创建！');window.location.href='".site_url('circle/create')."';</script>");
		}
		if($this->circle_admin_model->getCircleCount($data['creator']) >= 3){
			//die("<script>alert('您管理的圈子数量过多');window.location.href='".site_url('circle/create')."';</script>");
		}
		//save
		$this->circle_model->begin();
		$cid = $this->circle_model->createEntity($data);
		if($cid <= 0){
			die("<script>alert('创建失败，请稍后重试！');window.location.href='".site_url('circle/create')."';</script>");
		}
		$data = array(
				'circle_id' => $cid,
				'user_id'	=> $this->session->userdata('uid'),
				'is_primary'=> '1'
		);
		$res = $this->circle_admin_model->createEntity($data);
		if(!$res){
			$this->circle_model->rollback();
			die("<script>alert('创建失败，请稍后重试！');window.location.href='".site_url('circle/create')."';</script>");
		}
		$data = array(
				'circle_id'	=> $cid,
				'user_id'	=> $this->session->userdata('uid'),
				'is_joined'	=> '1'
		);
		$res = $this->circle_user_model->createEntity($data);
		if(!$res){
			$this->circle_model->rollback();
			die("<script>alert('创建失败，请稍后重试！');window.location.href='".site_url('circle/create')."';</script>");
		}
		
		$this->circle_model->commit();
		
		die("<script>alert('圈子创建成功');window.parent.location.href='".site_url('circle/view/'.$cid)."';window.parent.$.fancybox.close();</script>");
	}
	
	/**
	 * Assign Circle Admin
	 */
	public function assignAdmin(){
		$input = $this->input->post();
		print_r($input);die;
		if(empty($input['circle_id'])|| empty($input['user_id'])){
			$this->msgblock->addError('请正确输入信息！');
			redirect(site_url('circle'));
			return;
		}
		$circleInfo = $this->circle_admin_model->retrieve();
		if(1){}
		$data = array(
				'circle_category_id'	=>	$input['category'],
				'name'					=>	$input['name'],
				'description'			=>	$input['description'],
	
		);
	
		$this->circle_model->begin();
		$cid = $this->circle_model->createEntity($data);
		if($cid <= 0){
			$this->msgblock->addError('创建失败，请稍后重试！');
		}
		$circleAdmin = array(
				'circle_id' => $cid,
				'user_id'	=> $this->session->userdata('uid'),
				'is_primary'=> 1
		);
		$res = $this->circle_admin_model->createEntity($circleAdmin);
		if($res <= 0){
			$this->msgblock->addError('创建失败，请稍后重试！');
			$this->circle_model->rollback();
		}
	
		$this->circle_model->commit();
	
		$this->msgblock->addSuccess('圈子创建成功！');
	}
	
	public function view($circle_id){
		$circleInfo = $this->circle_model->getInfo($circle_id);
		if(!$this->circle_user_model->checkIsConcerned($this->session->userdata('uid'), $circle_id)){
			$conAct = '<div class="rep-concern active fr" onclick="btnConcern(this)">关注圈子</div>';
			$joinAct = '<div class="rep-join active fr" onclick="btnJoin(this)">申请加入</div>';
		} else{
			$conAct = '<div class="rep-concern fr" onclick="btnUnConcern(this)">取消关注</div>';
			if($this->circle_user_model->checkIsMember($this->session->userdata('uid'), $circle_id)){
				$joinAct = '<div class="rep-join fr" onclick="btnQuit(this)">退出圈子</div>';
			} else if($this->circle_applicant_model->checkIsApplying($this->session->userdata('uid'), $circle_id)){
				$joinAct = '<div class="rep-join fr" onclick="btnWaitCheck(this)">待审核</div>';
			}else{
				$joinAct = '<div class="rep-join active fr" onclick="btnJoin(this)">申请加入</div>';
			}
		}
		$data = array(
				'circleInfo'	=>	$circleInfo,
				'joinAct'		=>	$joinAct,
				'conAct'		=>	$conAct
		);
		$this->load->view('circle/view', $data);
	}
	
	public function viewMember($circle_id){
		$circleInfo = $this->circle_model->getInfo($circle_id);
		$data = array(
				'circleInfo'	=>	$circleInfo,
		);
		$this->load->view('circle/viewMember', $data);
	}
	
	/**
	 * get circle members
	 */
	public function getCircleMembers($cid){
		$input = $this->input->post();
		$pageSize = isset($input['amount'])?$input['amount']:5;
		$laseItem = isset($input['last'])?$input['last']:0;
		
		$data = $this->circle_user_model->getCircleMembers($cid, $pageSize, $laseItem);
		foreach ($data as $key => $val){
			$uInfo  = $this->user_model->getInfo($val['user_id']);
			$data[$key]['name'] = isset($uInfo['nickname'])?'<a href="'.site_url('user/view/'.$val['user_id']).'">'.$uInfo['nickname'].'</a>':'';
			$data[$key]['headportrait'] = '<a href="'.site_url('user/view/'.$val['user_id']).'"><img style="width:40px;" src="'.(isset($uInfo['headportrait'])?$uInfo['headportrait']:'').'" class="img-avatar"></a>';
		}

		echo json_encode($data);
	}
	
	/**
	 * get circle topics
	 */
	public function getCircleTopics($cid){
		$input = $this->input->post();
		$pageSize = isset($input['amount'])?$input['amount']:5;
		$laseItem = isset($input['last'])?$input['last']:0;
		
		$data = $this->topic_model->getCircleTopics($cid, $pageSize, $laseItem);
		foreach ($data as $key => $val){
			$uInfo  = $this->user_model->getInfo($val['user_id']);
			$data[$key] = array(
					'headportrait'	=>	'<a href="'.site_url('user/view/'.$val['user_id']).'"><img style="width:40px;" src="'.(isset($uInfo['headportrait'])?$uInfo['headportrait']:'').'" class="img-avatar"></a>',
					'name'			=>	isset($uInfo['nickname'])?'<a href="'.site_url('user/view/'.$val['user_id']).'">'.$uInfo['nickname'].'</a>':'',
					'title'			=>	'<a href="'.site_url('topic/view/'.$val['id']).'">'.$val['title'].'</a>',
					'topicphoto'	=>	($val['topic_img'])?'<img src="'.$val['topic_img'].'" href="'.$val['topic_img'].'" class="rep-img">':'',
					'content'		=>	htmlspecialchars_decode($val['content'])
			);
		}
		echo json_encode($data);
	}
	
	/**
	 * get user circles
	 */
// 	<div class="rep-concern active fr" onclick="btnConcern(this)">关注圈子</div>
// 	<div class="rep-concern fr" onclick="btnUnConcern(this)">取消关注</div>
// 	<div class="rep-join active fr" onclick="btnJoin(this)">申请加入</div>
// 	<div class="rep-join fr" onclick="btnWaitCheck(this)">待审核</div>
// 	<div class="rep-join fr" onclick="btnQuit(this)">退出圈子</div>
	public function getUserCircles(){
		$input = $this->input->post();
		$pageSize = isset($input['amount'])?$input['amount']:5;
		$laseItem = isset($input['last'])?$input['last']:0;
	
		$data = $this->circle_user_model->getUserConcernedCircles($this->session->userdata('uid'), $pageSize, $laseItem);
		$circleArr = array();
		foreach ($data as $key => $val){
			$cInfo  = $this->circle_model->getInfo($val['circle_id']);
			if($val['is_joined']){
				$joinAct = '<div class="rep-join fr" onclick="btnQuit(this)">退出圈子</div>';
			} else if($this->circle_applicant_model->checkIsApplying($this->session->userdata('uid'), $val['circle_id'])){
				$joinAct = '<div class="rep-join fr" onclick="btnWaitCheck(this)">待审核</div>';
			}else{
				$joinAct = '<div class="rep-join active fr" onclick="btnJoin(this)">申请加入</div>';
			}
			$topicArr = $this->topic_model->getCircleTopics($val['circle_id'],3);
			if(!count($topicArr)){
				$circleTopics = '<p class="circleTopics">该圈子暂无话题</p>';
			} else{
				$circleTopics = '';
				foreach ($topicArr as $topic){
					$circleTopics .= '<p class="circleTopics"><a href="'.site_url('topic/view/'.$topic['id']).'" class="link ellipsis-12em">'.$topic['title'].'</a><span class="time">'.$this->user_dynamic_model->getTimeFormat(strtotime($topic['updated_at'])).'</span></p>';
				}
			}
			$circleArr[] = array(
					'circle_name'	=>	'<a href="'.site_url('circle/view/'.$val['circle_id']).'">'.$cInfo['name'].'</a>',
					'circle_img'	=>	'<a href="'.site_url('circle/view/'.$val['circle_id']).'"><img width="80px" src="'.(isset($cInfo['circle_img'])?$cInfo['circle_img']:'').'" class="img-cir"></a>',
					'circle_id'		=>	$val['circle_id'],
					'circle_topics'	=>	$circleTopics,
					'action'		=>	'<div class="rep-concern fr" onclick="btnUnConcern(this)">取消关注</div>'.$joinAct
			);
		}
	
		echo json_encode($circleArr);
	}
	
	/**
	 * get all circles
	 */
	public function getAllCircles(){
		$input = $this->input->post();
		$pageSize = isset($input['amount'])?$input['amount']:5;
		$laseItem = isset($input['last'])?$input['last']:0;
		$cateId = $this->input->get('categoryId');
		$keyword = $this->input->get('keyword');
		
		$cond = array();
		if($cateId){
			$cond['circle_category_id'] = $cateId;
		}
		$like = array();
		if($keyword){
			$like['name']	= $keyword;
		}
		$data = $this->circle_model->getAllCircles($pageSize, $laseItem, $cond, $like);
		$circleArr = array();
		foreach ($data as $cInfo){
			if(!$this->circle_user_model->checkIsConcerned($this->session->userdata('uid'), $cInfo['id'])){
				$conAct = '<div class="rep-concern active fr" onclick="btnConcern(this)">关注圈子</div>';
				$joinAct = '<div class="rep-join active fr" onclick="btnJoin(this)">申请加入</div>';
			} else{
				$conAct = '<div class="rep-concern fr" onclick="btnUnConcern(this)">取消关注</div>';
				if($this->circle_user_model->checkIsMember($this->session->userdata('uid'), $cInfo['id'])){
					$joinAct = '<div class="rep-join fr" onclick="btnQuit(this)">退出圈子</div>';
				} else if($this->circle_applicant_model->checkIsApplying($this->session->userdata('uid'), $cInfo['id'])){
					$joinAct = '<div class="rep-join fr" onclick="btnWaitCheck(this)">待审核</div>';
				}else{
					$joinAct = '<div class="rep-join active fr" onclick="btnJoin(this)">申请加入</div>';
				}
			}
			$topicArr = $this->topic_model->getCircleTopics($cInfo['id'],3);
			if(!count($topicArr)){
				$circleTopics = '<p class="circleTopics">该圈子暂无话题</p>';
			} else{
				$circleTopics = '';
				foreach ($topicArr as $topic){
					$circleTopics .= '<p class="circleTopics"><a href="'.site_url('topic/view/'.$topic['id']).'" class="link ellipsis-12em">'.$topic['title'].'</a><span class="time">'.$this->user_dynamic_model->getTimeFormat(strtotime($topic['updated_at'])).'</span></p>';
				}
			}
			$circleArr[] = array(
					'circle_name'	=>	'<a href="'.site_url('circle/view/'.$cInfo['id']).'">'.$cInfo['name'].'</a>',
					'circle_img'	=>	'<a href="'.site_url('circle/view/'.$cInfo['id']).'"><img width="80px" src="'.(isset($cInfo['circle_img'])?$cInfo['circle_img']:'').'" class="img-cir"></a>',
					'circle_id'		=>	$cInfo['id'],
					'circle_topics'	=>	$circleTopics,
					'action'		=>	$conAct.$joinAct
			);
		}
	
		echo json_encode($circleArr);
	}
	
	public function userAction(){
		$input = $this->input->post();
		if(empty($input['action'])|| empty($input['circle_id'])){
			$this->apioutput->apiResponseError('非法请求，请联系管理员！');
		}
		$cid = $input['circle_id'];
		$uid = $this->session->userdata('uid');
		$circleInfo = $this->circle_model->getInfo($cid);
		if(!$circleInfo){
			$this->apioutput->apiResponseError('您申请加入的圈子不存在！');
		}
		
		switch ($input['action']){
			case 'concern':
				if($this->circle_user_model->checkIsConcerned($uid, $cid) == TRUE){
					$this->apioutput->apiResponseError('您已经关注过该圈，请勿重复提交申请！');
				}
				
				$data = array(
						'circle_id'	=>	$cid,
						'user_id'	=>	$uid
				);
				$res = $this->circle_user_model->createEntity($data);
				if($res <= 0){
					$this->apioutput->apiResponseError('关注失败，请稍后重试！');
				}
				
				$this->apioutput->apiResponseSuccess();
				break;
			case 'unconcern':
				if(!$this->circle_user_model->checkIsConcerned($uid, $cid) == TRUE){
					$this->apioutput->apiResponseError('您尚未关注该圈！');
				}

				$this->circle_user_model->begin();

				if($this->circle_user_model->checkIsMember($uid, $cid) == TRUE){
					if($circleInfo['user_number']-1 >= 0){
						$uno = $circleInfo['user_number']-1;
					}else{
						$uno = 0;
					}
					$res = $this->circle_model->updateInfo($cid,array('user_number' => $uno));
					if($res <= 0){
						$this->circle_user_model->rollback();
						$this->apioutput->apiResponseError('关注失败，请稍后重试！');
					}
				}
				$res = $this->circle_user_model->unconcern($uid, $cid);
				if(!$res){
					$this->circle_user_model->rollback();
					$this->apioutput->apiResponseError('取消关注失败，请稍后重试！');
				}
				$res = $this->circle_applicant_model->cleardata($uid, $cid);
				if(!$res){
					$this->circle_user_model->rollback();
					$this->apioutput->apiResponseError('取消关注失败，请稍后重试！');
				}
				
				$this->circle_user_model->commit();
				
				$this->apioutput->apiResponseSuccess();
				break;
				$this->apioutput->apiResponseSuccess();
				break;
			case 'join':
				if($this->circle_user_model->checkIsMember($uid, $cid) == TRUE || $this->circle_applicant_model->checkIsApplying($uid, $cid) == TRUE){
					$this->apioutput->apiResponseError('您已经加入或申请加入过该圈，请勿重复提交申请！');
				}
				
				$this->circle_user_model->begin();
				$data = array(
						'circle_id'	=>	$cid,
						'user_id'	=>	$uid
				);
				if($this->circle_user_model->checkIsConcerned($uid, $cid) != TRUE){
					$res = $this->circle_user_model->createEntity($data);
					if($res <= 0){
						$this->apioutput->apiResponseError('申请加入失败，请稍后重试！');
					}
				}
				$res = $this->circle_applicant_model->createEntity($data);
				if(!$res){
					$this->circle_user_model->rollback();
					$this->apioutput->apiResponseError('申请加入失败，请稍后重试！');
				}
				
				$this->circle_user_model->commit();
				
				$this->apioutput->apiResponseSuccess();
				break;
			case 'quit':
				if($this->circle_user_model->checkIsMember($uid, $cid) != TRUE){
					$this->apioutput->apiResponseError('您不是该圈的成员！');
				}
				
				$this->circle_user_model->begin();
				$res = $this->circle_user_model->quitcircle($uid, $cid);
				if(!$res){
					$this->circle_user_model->rollback();
					$this->apioutput->apiResponseError('取消关注失败，请稍后重试！');
				}
				$res = $this->circle_applicant_model->cleardata($uid, $cid);
				if(!$res){
					$this->circle_user_model->rollback();
					$this->apioutput->apiResponseError('取消关注失败，请稍后重试！');
				}
				
				$this->circle_user_model->commit();
				
				$this->apioutput->apiResponseSuccess();
				break;
			default:
				$this->apioutput->apiResponseError('非法请求，请联系管理员！');
		}
		
		if($this->circle_user_model->checkIsMember($uid, $cid) == TRUE){
			$this->msgblock->addError('您已经加入过该圈，请勿重复提交申请！');
			$this->apioutput->apiResponseError('您已经加入过该圈，请勿重复提交申请！');
		}
		
		$this->apioutput->apiResponseSuccess();
	}
	
	/**
	 * 
	 */
	public function joinCircle($cid){
		$data = array(
				'circle_id'	=>	$cid,
				'user_id'	=>	$this->session->userdata('uid')
		);
		$circleInfo = $this->circle_model->getInfo($cid);
		if(!$circleInfo){
			$this->msgblock->addError('您申请加入的圈子不存在！');
			$this->apioutput->apiResponseError('您申请加入的圈子不存在！');
		}
		if($this->circle_user_model->checkIsMember($data['user_id'], $cid) == TRUE){
			$this->msgblock->addError('您已经加入过该圈，请勿重复提交申请！');
			$this->apioutput->apiResponseError('您已经加入过该圈，请勿重复提交申请！');
		}
		$this->circle_user_model->begin();
		$res = $this->circle_user_model->createEntity($data);
		if($res <= 0){
			$this->msgblock->addError('关注失败，请稍后重试！');
			$this->apioutput->apiResponseError('关注失败，请稍后重试！');
		}
		$this->circle_model->updateInfo($cid,array('user_number' => ($circleInfo['user_number']+1)));
		if($res <= 0){
			$this->msgblock->addError('关注失败，请稍后重试！');
			$this->circle_user_model->rollback();
			$this->apioutput->apiResponseError('关注失败，请稍后重试！');
		}
		
		$this->circle_user_model->commit();
		
		$this->apioutput->apiResponseSuccess();
	}
	
	public function concernCircle($cid){
		$data = array(
				'circle_id'	=>	$cid,
				'user_id'	=>	$this->session->userdata('uid')
		);
		$circleInfo = $this->circle_model->getInfo($cid);
		if(!$circleInfo){
			$this->msgblock->addError('您申请关注的圈子不存在！');
			$this->apioutput->apiResponseError('您申请关注的圈子不存在！');
		}
		if($this->circle_user_model->checkIsMember($data['user_id'], $cid) == TRUE){
			$this->msgblock->addError('您已经关注过该圈，请勿重复提交申请！');
			$this->apioutput->apiResponseError('您已经关注过该圈，请勿重复提交申请！');
		}
		$this->circle_user_model->begin();
		$res = $this->circle_user_model->createEntity($data);
		if($res <= 0){
			$this->msgblock->addError('关注失败，请稍后重试！');
			$this->apioutput->apiResponseError('关注失败，请稍后重试！');
		}
		$this->circle_model->updateInfo($cid,array('user_number' => ($circleInfo['user_number']+1)));
		if($res <= 0){
			$this->msgblock->addError('关注失败，请稍后重试！');
			$this->circle_user_model->rollback();
			$this->apioutput->apiResponseError('关注失败，请稍后重试！');
		}
		
		$this->circle_user_model->commit();
		
		$this->apioutput->apiResponseSuccess();
	}
}